package engine.newUi
{
	import engine.control.TurnPapersViewGroup;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.Record;
	import engine.data.ResPath;
	import engine.data.View;
	import engine.flag.ResourcesPath;
	import engine.logic.DoubleClickManager;
	import engine.logic.LogSendLogic;
	import engine.logic.MenuListManager;
	import engine.logic.login.NxCallLater;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.scene.player.MoveAction;
	import engine.tip.TipsMainLogic;
	import engine.ui.AlertUI;
	import engine.util.FilterUtil;
	
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	import flash.sampler.startSampling;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.button.NxButton;
	import newx.com.control.group.NxViewGroup;
	import newx.com.control.tab.NxTab;
	import newx.com.control.table.NxTableEvent;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;
	import newx.utils.MouseHandle;
	
	/**
	 * 帮派商人
	 * @author yangyuechao
	 */
	public class FamilyShopLogic
	{
		/**
		 * 0,
		 * 1,白
		 * 2.绿
		 * 3.蓝
		 * 4.紫红
		 * 5.橙黄
		 * 6.黄
		 * 7.浅黄
		 */		
		protected const COLOR_TABLE	:Array	=	["","#ffffff'>","#1eff00'>","#20BFF8'>","#a335ee'>","#E8912E'>","#e5cc80'>","#ffff00'>"];
		private static var _self:FamilyShopLogic
		
		private var _myDis:FamilyShopUI;
		private var _model:ModelLocator;
		private var _bindManage:BindManage;
		
		private var _blindFlag:int = -1;
		private var _blindIndex:int = -1;
		
		//管理翻页
//		private var _pageTurn:TurnPapersViewGroup;
		
		private var itemGroup:NxViewGroup;
		
		private var _familyLevel:int = 0;
		
//		private var _currentPage:int;
//		private var _allPage:int;
		private var _count:int = 10;
		private var _allMouseOverArr:Array;
		
		private var _currentID:int;
		
		private var _itemMc:MovieClip;
		private var _itemBtn:SimpleButton;
		
		private var _itemsArr:Array;
		private var _showItems:Array;
		
		private var _strArr:Vector.<strInfo>;
		private const MAX_ITEM_NUM:int=17*3;
		
		private var record:Record;
		
		//获取消耗积分
		private var _needUseArr:Array;
		
		private var _allItemBtn:SimpleButton;
		
		//下一级道具列表
		private var _nextItem:Array;
		
		public function FamilyShopLogic()
		{
			
		}
		
		public static function getInstance():FamilyShopLogic
		{
			if(_self == null)
			{
				_self = new FamilyShopLogic();
			}
			return _self;
		}
		
		public function Init():void
		{
			_bindManage			=	BindManage.getInstance();
			_model				=	ModelLocator.getInstance();
			_myDis				=	FamilyShopUI.getInstance();
			itemGroup			=	_myDis.viewGroup;
			_myDis.text.autoScroll=true;
//			_pageTurn			= new TurnPapersViewGroup(_myDis.viewGroup, _myDis.btnPre, _myDis.btnNext, 
//				showItem, removeItem, afterTurn, _myDis.pagelabel);
			initNxViewGroup();
		}
		
		public function AfterHide():void
		{
			removeListener();
			for(var i:int = 0; i < _count; i++){
				var _mc:MovieClip = itemGroup.getItemByIndex(i);
				removeItem(_mc);
			}
			_myDis.text.htmlText = "";
			_strArr = null;
			_itemsArr = [];
			_showItems = [];
			_allItemBtn = null;
			record = null;
		}
		
		public function BeforeShow():void
		{
//			_currentPage = 1;
			_strArr = new Vector.<strInfo>();
			_nextItem = new Array();
			_allItemBtn = itemGroup.getItemByIndex(0)["btn"] as SimpleButton;
			getUseScore();
			resloveData();
			addListener();
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_REQUEST_GUILD_TRADE_LOG);
		}
		
		/**
		 * 开始监听
		 */	
		public function addListener():void
		{
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_TRADE), getServerDate);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_TRADE_LOG), getStrInfo);
			_myDis.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE, closeWindowHandle);
//			_pageTurn.addListener();
			_myDis.mc2.addEventListener(MouseEvent.MOUSE_OVER, showOver);
			_myDis.mc2.addEventListener(MouseEvent.MOUSE_OUT, onCloseTips);
			_myDis.text.addLinkClickHandel(onClickText);
			
			if(_blindIndex == -1)
			{
				_blindIndex = _bindManage.BindProp(_model.scene.Role,"GuildScore", this, "score");
			}
			//绑定表格
			if(_blindFlag == -1)
			{
				_blindFlag= _bindManage.BindRecord(_model.scene,"GuildTradeRec",onaddPerHandle,onremovePerHandle);
			}
		}
		
		/**
		 * 移除监听
		 */		
		public function removeListener():void
		{
			_model.removeEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_TRADE), getServerDate);
			_model.removeEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_TRADE_LOG), getStrInfo);
			_myDis.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE, closeWindowHandle);
//			_pageTurn.removeListener();
			_myDis.mc2.removeEventListener(MouseEvent.MOUSE_OVER, showOver);
			_myDis.mc2.removeEventListener(MouseEvent.MOUSE_OUT, onCloseTips);
			_myDis.text.removeLinkClickHandel();
			_myDis.text.removeEventListener(MouseEvent.MOUSE_OUT, onCloseTips);
			
			if(_blindIndex != -1)
			{
				_blindIndex = _bindManage.UnbindProp(_model.scene.Role, "GuildScore", _blindIndex);
			}
			if(_blindFlag!=-1)
			{
				_blindFlag= _bindManage.UnbindRecord("GuildTradeRec", _blindFlag);
			}
		}
		
		/**
		 * 关闭窗口 
		 */		
		private function closeWindowHandle(e:NxWindowEvent):void
		{
			_myDis.hide();
		}
		
		/**
		 *	添加
		 */  
		private function onaddPerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			if(record == null) return;
			if(PropertiesValue[0] != _familyLevel) return;
			var _tempArr:Array = record.recArr;
			var len:int = _tempArr.length;
			var configid:int;
			var num:int;
			for(var i:int = 0; i < len; i ++){
				configid	= _tempArr[i][1];
				if(PropertiesValue[1] == configid){
					record.recArr[i][2] = PropertiesValue[2];
				}
			}
			
			_tempArr = record.recArr;
			resolveRecord(_tempArr);
		}
		
		/**
		 *  取消
		 */
		private function onremovePerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			
		}
		
		/**
		 * 获取所需消耗积分
		 */
		private function getUseScore():void
		{
			_needUseArr = [];
			_itemsArr = StaticIni.getIniVar("allId", "List").split(",");
			
			if(_itemsArr.length == 0) return;
			
			for(var i:int = 0; i < _itemsArr.length; i++){
				var level:String	= StaticIni.getIniVar(("Card_" + _itemsArr[i]), "Level");
				var buysocre:String	= StaticIni.getIniVar(("Card_" + _itemsArr[i]), "BuyScore");
				var _tempArr:Array = new Array();
				_tempArr.push(_itemsArr[i], int(level), int(buysocre));
				_needUseArr.push(_tempArr);
			}
		}
		
		/**
		 *初始化viewGroup 
		 * 
		 */		
		private function initNxViewGroup():void
		{
			var itemMC:MovieClip;
			for( var i : int = 0; i < _count; i++ )
			{
				itemMC = itemGroup.getItemByIndex(i);
				itemMC.visible = false;
				itemMC["index"] 	= 	i;
				var img:NxClip = new NxClip;
				img.defaultSkin = "NotFound6";
				img.isCache 	= true;
				img.x = 25;
				img.y = 13;
				img.visible = false;
				itemMC.addChild(img);
				var count:NxLabel = new NxLabel;
				count.x = 24;
				count.y = 10;
				itemMC.addChild(count);
				itemMC["img"]	= img;
				itemMC["count"] = count;
				itemMC["count"].visible = false;
//				itemMC["img"].addEventListener( MouseEvent.MOUSE_OVER,showUpTips );
//				itemMC["img"].addEventListener( MouseEvent.MOUSE_OUT,onCloseTips );
				itemMC.addEventListener( MouseEvent.MOUSE_OVER,showUpTips );
				itemMC.addEventListener( MouseEvent.MOUSE_OUT,onCloseTips );
				itemMC["titleTxt1"].mouseEnabled  = false;
				itemMC["titleTxt1"].htmlText = StaticIni.getSwfLangStr("UIString_1000002");
				itemMC["titleTxt2"].htmlText = "";
				itemMC["btn"].addEventListener(MouseEvent.CLICK, btnHandler);
				itemMC["btn"].filters = [FilterUtil.GrayColorFilter];
				itemMC["btn"].enabled = false;
				itemMC["btn"].mouseEnabled = false;
			}
		}
		
		/**
		 * 显示TIPS
		 */
		private function showUpTips(e:MouseEvent):void
		{
			_itemMc = e.currentTarget as MovieClip;
			var target:MovieClip = e.currentTarget as MovieClip;
			var dateils:Object	=	target["data"];
			if(dateils ==null) return;
			var str:String = "";
			str += StaticIni.getSwfLangStrVar("FamilyShop_" + dateils["NameID"], [dateils["score"]]);
			if(dateils["Level"] > _familyLevel)  return;//{
//				str += "<br>";
//				str += StaticIni.getSwfLangStrVar("UIString_1000587", [dateils["Level"]]);
//			}
			TipsMainLogic.instance.showString(str);
		}
		
		private function showOver(e:MouseEvent):void
		{
			var target:DisplayObjectContainer = e.currentTarget as DisplayObjectContainer;
			
			switch(target){
				case _myDis.mc2:
					TipsMainLogic.instance.showString(StaticIni.getSwfLangStr("UIString_1000585"));
					break;
			}
		}
		
		/**
		 * 移除TIPS
		 */
		private function onCloseTips(e:MouseEvent):void
		{
			_itemMc = null;
			TipsMainLogic.instance.hide();
		}
		
		/**
		 * 玩家积分
		 */		
		public function set score(val:int):void
		{
			_myDis.myLabel.htmlText	= "<font color='#1eff00'>" + val + "</font>" + StaticIni.getSwfLangStr("UIString_1000685");
		}
		
		/**
		 * 是否购买
		 */
		private function btnHandler(e:MouseEvent):void
		{
			_itemBtn = e.currentTarget as SimpleButton;
			var dateils:Object	=	_itemBtn.parent["data"];
			if(dateils ==null) return;
			_currentID = dateils["NameID"];
			SitAlerLogic.getIntatic().setUIinfo(StaticIni.getSwfLangStr("UIStr_1000825"), [], enterHandler, _allItemBtn);
		}
		
		private function enterHandler():void
		{
			SystemSender.getInstance().CustomMsg(
				CustomToServerFlag.CLIENT_CUSTOMMSG_TRADE_WITHNPC,0,View.VIEWFAMILY_SHOP,_currentID,-1,1);
		}
		
		/**
		 * 接受数据
		 * [积分，等级，经验]
		 */
		private function getServerDate(e:CustomMsgEvent):void
		{
			var serverArr:Array = e.pList;
			
			if(serverArr.length == 0) return;
			
			_familyLevel			= serverArr[0];
			_myDis.label2.htmlText = StaticIni.getSwfLangStrVar("UIString_1000588", [_familyLevel]);
			var allExp:int = int(StaticIni.getIniVar("familyUP_"+_familyLevel,"exp"));
			if(_familyLevel == 5 && (allExp - serverArr[1]) == 0){
				_myDis.label3.visible = false;
			} else {
				_myDis.label3.visible = true;
				_myDis.label3.htmlText = StaticIni.getSwfLangStrVar("UIString_1000589", [(allExp - serverArr[1]), (_familyLevel + 1)]);
			}
			
			var per:Number = serverArr[1] / allExp;
			_myDis.loading.bar = int(per * 100);
			
			//解析购买记录
			if(serverArr.length > 2){
				var _tempArr:Array = serverArr.slice(2, serverArr.length);
				savStrInfo(_tempArr);
			}
			
			record = _model.scene.GetRecordEx("GuildTradeRec");
			var _showArr:Array = record.recArr;
			resolveRecord(_showArr);
		}
		
		/**
		 * 刷新次数
		 */
		private function resolveRecord(_showArr:Array):void
		{
			var len:int	= _showArr.length;
			var _tempArr:Array = new Array();
			var level:int;
			var configid:int;
			var num:int;
			var data:Object;
			for(var i:int = 0; i < len; i ++){
				level	= _showArr[i][0];
				if(level == _familyLevel){
					_tempArr.push(_showArr[i]);
				}
			}
			for(i = 0;i < _tempArr.length; i++){
				configid	= _tempArr[i][1];
				num			= _tempArr[i][2];
				for(var j:int = 0; j < _count; j++){
					var _mc:MovieClip = itemGroup.getItemByIndex(j);
					data = _mc["data"];
					if(data && data["NameID"] == configid){
						for(var z:int = 0; z < _needUseArr.length; z++ ){
							if(_needUseArr[z][0] == configid && _needUseArr[z][1] <= _familyLevel){
								data["NameID"]		= configid;
								data["Num"]			= num;
								showItem(_mc, data);
							}
						}
					}
				}
			}
			setNextGroup();
		}
		
		/**
		 * 刷新TIPS数据
		 */
		private function refreshTips(mc:MovieClip, num:int):void
		{
//			TipsMainLogic.instance.hide();
//			var str:String = "";
////			var tObj:Object	= TipsMainLogic.instance.getStaticObjWithID(dateils["NameID"] + "");
////			TipsMainLogic.instance.showMain( tObj );
//			str += StaticIni.getSwfLangStr(StaticIni.getIniVar(int(_itemMc["data"]["NameID"]),"NameID"));
//			str += "<br>";
//			str += StaticIni.getSwfLangStrVar("UIString_1000590", [_itemMc["data"]["score"]]);
//			str += "<br>";
//			if(num == -1){
//				str +=  StaticIni.getSwfLangStr("UIString_1000591");
//			} else {
//				str +=  StaticIni.getSwfLangStrVar("UIString_1000586", [num]);
//			}
//			TipsMainLogic.instance.showString(str);
			
			if(num == -1){
				mc["count"].htmlText = "∞";
			} else {
				mc["count"].htmlText = "x" + num;
			}
		}
		
		/**
		 * 解析配置信息
		 */
		private function resloveData():void
		{	
			if(_needUseArr.length == 0) return;
			
//			_pageTurn.clear();
			var len:int		= _needUseArr.length;
			var data:Object;
			var j:int = 0;
			var _mc:MovieClip;
			for(var i:int = 0; i < len; i ++){
				if(j > 9) return;
				_mc = itemGroup.getItemByIndex(j);
				_mc.visible = true;
				data = new Object;
				data["NameID"]		= _needUseArr[i][0];
				if(data["NameID"] == 39011115){
					data["Photo"]		= ResourcesPath.getPropsURL(45003005);
				} else {
					data["Photo"]		= ResourcesPath.getPropsURL(data["NameID"]);
				}
				data["Level"]		= _needUseArr[i][1];
				data["Num"]			= 0;
				data["score"]		= _needUseArr[i][2];
				initItem(_mc, data);
				j++;
			}
			
//			var _itemNum:int = int(Math.floor(len / _jiange));
//			_allPage		= int(Math.ceil(_itemNum / _count));
//			setPageIndex(_allPage);
			
//			_pageTurn.dataProvider = _itemsArr;
		}
		
		/**
		 *初始化图像 
		 * @param mc
		 * @param data
		 * 
		 */		
		private function initItem(mc:MovieClip, data:Object):void
		{
			mc["img"].visible			= false;
			mc["titleTxt2"].htmlText 	= "未开启";
			mc["titleTxt2"].filters	= [FilterUtil.GrayColorFilter];
			mc["titleTxt1"].filters	= [FilterUtil.GrayColorFilter];
			mc["btn"].enabled			= false;
			mc["btn"].mouseEnabled		= false;
			mc["btn"].filters			= [FilterUtil.GrayColorFilter];
			mc["data"]					= data;
			if(mc["data"]["Level"] == (_model.scene.Role.GetProperties("GuildLevel") + 1)){
				_nextItem.push(mc["data"]);
			}
		}
		
		/**
		 * 填充viewgroup
		 */
		private function showItem(mc:MovieClip,data:Object):void
		{
			mc["img"].source	=	data["Photo"];
			mc["img"].visible = true;
			mc["titleTxt2"].htmlText 	=	StaticIni.getSwfLangStr(StaticIni.getIniVar(int(data["NameID"]),"NameID"));
			if(data["Num"] > 0 || data["Num"] == -1){
				if(data["Num"] == -1){
					mc["count"].htmlText = "∞";
				} else {
					mc["count"].htmlText = "x" + data["Num"];
				}
				mc["count"].visible = true;
				mc["img"].filters = [];
				mc["btn"].filters = [];
				mc["titleTxt2"].filters  = [];
				mc["titleTxt1"].filters  = [];
				mc["btn"].enabled	=	true;
				mc["btn"].mouseEnabled = true;
				mc["titleTxt2"].filters  = [];
				mc["titleTxt1"].filters  = [];
			} else {
				mc["count"].visible = false;
				mc["img"].filters = [FilterUtil.GrayColorFilter];
				mc["btn"].filters = [FilterUtil.GrayColorFilter];
				mc["titleTxt2"].filters  = [FilterUtil.GrayColorFilter];
				mc["titleTxt1"].filters  = [FilterUtil.GrayColorFilter];
				mc["btn"].enabled	=	false;
				mc["btn"].mouseEnabled = false;
			}
			mc["data"]					=	data;
			if(_itemMc && _itemMc["data"]["NameID"] == mc["data"]["NameID"]){
				refreshTips(mc, data["Num"]);
			}
		}
		
		/**
		 * 清空viewgroup
		 */
		private function removeItem(mc:MovieClip):void
		{
			mc["img"].clear();
			mc["img"].source				=	null;
			mc["count"].htmlText			=	"";
			mc["titleTxt2"].htmlText 		=	"";
			mc["data"]						=	null;
		}
		
		/**
		 *设置下一级道具 
		 * 
		 */		
		private function setNextGroup():void
		{
			_myDis.nextGroup.col = _nextItem.length;
			var itemMC:MovieClip;
			for(var i:int = 0; i < _nextItem.length; i++){
				itemMC = _myDis.nextGroup.getItemByIndex(i);
				var img:NxClip = new NxClip;
				img.defaultSkin = "NotFound6";
				img.isCache 	= true;
				img.source		= _nextItem[i]["Photo"];
				img.x = 18;
				img.y = 13;
				itemMC.addChild(img);
				itemMC["titleTxt2"].htmlText	= StaticIni.getSwfLangStr(StaticIni.getIniVar(int(_nextItem[i]["NameID"]),"NameID"));
				itemMC.addEventListener(MouseEvent.ROLL_OVER, nextShowHandler);
				itemMC.addEventListener(MouseEvent.ROLL_OUT, nextOutHandler);
				itemMC["data"] = _nextItem[i];
			}
		}
		
		private function nextShowHandler(e:MouseEvent):void
		{
			var target:MovieClip = e.currentTarget as MovieClip;
			var dateils:Object	=	target["data"];
			if(dateils ==null) return;
			var str:String = "";
			str += StaticIni.getSwfLangStrVar("FamilyShop_" + dateils["NameID"], [dateils["score"]]);
			TipsMainLogic.instance.showString(str);
		}
		
		private function nextOutHandler(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();	
		}
		
		/**
		 * 翻页后的操作
		 */
		private function afterTurn():void
		{
			
		}
		
		/**
		 *获取所有玩家购买的信息 
		 * @param e
		 * 
		 */		
		private function getStrInfo(e:CustomMsgEvent=null):void
		{
			_strArr=new Vector.<strInfo>();
			var arr:Array=e.pList;
			
			if(arr.length>MAX_ITEM_NUM)
			{
				var len:int =arr.length-MAX_ITEM_NUM;
				arr.splice(0,len);
			}
			savStrInfo(arr);
			
			
		}
		/**
		 *保存购买信息数据 
		 * @param arr
		 * 
		 */		
		private function savStrInfo(arr:Array):void
		{
			for(var i:int=0;i< arr.length;i+=2)
			{
				_strArr.push(new strInfo(arr[i],arr[i+1],1));
			}
			showLog();
		}
		
		/**
		 * 购买记录
		 */
		private function showLog():void
		{
			var arr:Array=[];
			for(var i:String in _strArr)
			{
				arr=setStr(_strArr[int(i)]);
				var str:String	=	"<a href=\"event:" 
					+  _strArr[int(i)].name + "," +"\">"
					+  arr[0] + "</a>"
					+arr[1]
					+"<a href=\"event:item_"+"," 
					+_strArr[int(i)].configID +"\">"
					+ link_color(arr[2],arr[3])
					+"</a>";
				_myDis.text.htmlText += str;
			}
		}
		
		protected function link_color(str:String,color:int):String
		{
			if(color < 1 || color >8)
			{
				color	=	1;
			}
			return ("<font color ='"+COLOR_TABLE[color]+str+"</font>");
		}
		
		/**
		 *获取字符串数据 
		 * @param strVo
		 * @return 0 前缀 1物品名字 2物品颜色 3 购买的数量
		 * 
		 */		
		private function setStr(strVo:strInfo):Array
		{
			var str:String="";
			var itemObj:Object=StaticIni.getIniObj(strVo.configID);
			var titalStr:String=StaticIni.getSwfLangStrVar("UIString_1000333",[strVo.name]);
			var name:String=StaticIni.getSwfLangStr(itemObj["NameID"]);
			var midst:String=StaticIni.getSwfLangStr("UIString_1000334"); //购买了
			return [titalStr,midst,name,int(itemObj["Color"])] ;
		}
		
		/**点击文本超链接 
		 * @param val
		 * 
		 */		
		private function onClickText(val:String):void
		{
			if( val.indexOf("item_") != -1 )
			{
				//点击的是装备,道具的时候
				onShowItem(val);
				return;
			}
			var eplist:Array=val.split(",");
			if(_model.scene.Role.getPlayerName() == eplist[0]) return;
			MenuListManager.clickPlayer(eplist[0]);
		}
		
		/**
		 * 	显示道具tips
		 */
		private function onShowItem(tips : String):void
		{
			TipsMainLogic.instance.hide();
			var tipsList : Array = tips.split(",");
			var configID : int = tipsList[1];
			var tObj:Object=TipsMainLogic.instance.getStaticObjWithID(configID+"");
			TipsMainLogic.instance.showMain( tObj );
			_myDis.text.addEventListener(MouseEvent.MOUSE_OUT, onCloseTips);
		}
	}
}
class strInfo
{
	public var name:String;   //玩家名字
	public var configID:String; //物品ID
	public var amout:int;    //数量
	
	public function strInfo(name:String, configID:String, amout:int):void
	{
		this.name = name;
		this.configID = configID;
		this.amout = amout;
	}
}
class scoreInfo
{
	public var configid:int;	//道具ID
	public var level:int;		//所需等级
	public var score:int;		//消耗积分
	
	public function scoreInfo(configid:int, level:int, score:int):void
	{
		this.configid = configid;
		this.level = level;
		this.score = score;
	}
}